package com.laicunba.event.listener;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.laicunba.event.RateIncrCouponCreateEvent;
import com.laicunba.pojo.RateIncrCouponDO;
import com.laicunba.pojo.RegistryDO;
import com.laicunba.pojo.TemplateDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.service.MarketingMobileMessageService;
import com.laicunba.service.RegistryService;
import com.laicunba.service.TemplateService;
import com.laicunba.service.UserService;
import com.laicunba.util.DateUtil;

@Component
public class RateIncrCouponCreateEventListener implements ApplicationListener<RateIncrCouponCreateEvent> {
	private static final Logger LOG = Logger.getLogger(RateIncrCouponCreateEventListener.class);
	
	@Autowired
	private MarketingMobileMessageService marketingMobileMessageService;
	@Autowired
	private TemplateService templateService;
	@Autowired
	private UserService userService;
	@Autowired
	private RegistryService registryService;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void onApplicationEvent(RateIncrCouponCreateEvent event) {
		TemplateDO templateDO = templateService.findByCodeWidthDefault("GIVE_RATE_INCR_COUPON");
		RateIncrCouponDO couponDO = (RateIncrCouponDO) event.getSource();
		Map param = new HashMap();
		param.put("couponName", couponDO.getName());
		param.put("EndTime", DateUtil.formatDate(couponDO.getEndTime()));
		param.put("Rate", couponDO.getRate().toString()+"%");

		String message = templateService.simpleMerge(templateDO.getContent(), param);
		UserDO userDO = userService.get(UserDO.class, couponDO.getUserId());
		RegistryDO registry = registryService.get(RegistryDO.class, "sys.marketing-mobile-message.switch");
		if(registry != null && "ym".equalsIgnoreCase(registry.getVal())) {
			marketingMobileMessageService.sendMsgAsyncByYm(userDO.getMobile(), message);
		} else if(registry != null && "yr".equalsIgnoreCase(registry.getVal())) {
			marketingMobileMessageService.sendMsgAsyncByYr(userDO.getMobile(), message);
		} else {
			LOG.warn(String.format("加息券短信未发送警告：注册表营销短信设置为空或内容为空"));
		}
	}

}
